package org.java.net.socket;

import java.io.*;
import java.net.*;

public class Server3 {
	
	private DataInputStream reader;  //输入流
	private DataOutputStream writer;  //输出流
	private ServerSocket server;
	private Socket socket;
	
	public Server3(){}
	
	void startServer()
	{
		try
		{
			server = new ServerSocket(4747);
			System.out.println("服务器套接字被创建成功");
			
			while(true)
			{
				System.out.println("等待客户机连接请求");
				socket = server.accept();
				System.out.println("连接客户机完毕");
				
				reader = new DataInputStream(socket.getInputStream());
				writer = new DataOutputStream(socket.getOutputStream());
				
				getCommand();
			}
		}
		catch(Exception e)
		{
			System.out.println("....." + e);
		}
	}
	
	void getCommand()
	{
		try
		{
			while(true)
			{
				String fileName = reader.readUTF();  //获取文件名
				
				//想客户端发送文件内容
				writer.writeUTF(getFileInfo(fileName));
				writer.flush();
				
				System.out.println(fileName + "的信息传送完毕");
			}
		}
		catch(Exception e)
		{
		}
		finally
		{
			System.out.println("与客户机的连接中断");
			try
			{
				if(reader != null)
					reader.close();
				if(writer != null)
					writer.close();
				if(socket != null)
					socket.close();
				reader = null;
				writer = null;
				socket = null;
			}
			catch(IOException ie)
			{}
		}
	}
	
	//返回fileName文件的内容
	String getFileInfo(String fileName)
	{
		String fileInfo = "";
		
		try
		{
			FileReader fr = new FileReader(fileName);
			BufferedReader br = new BufferedReader(fr);
			
			String temp;
			while((temp=br.readLine()) != null)
			{
				fileInfo += temp + "\n";
				br.close();
			}
		}
		catch(FileNotFoundException fe)
		{
			fileInfo = "文件不存在";
		}
		catch(IOException ie)
		{}
		
		return fileInfo;
	}
	
	public static void main(String[] args)
	{
		Server3 server = new Server3();
		server.startServer();
	}
}
